import { normalizeAuthConfig, hasPermission, addVueCss } from './index.js';

/**
 * 路由级别的权限控制
 * 配置方式：
 * 在路由的meta字段中添加permission字段，值为权限配置对象
 * permission字段配置对象格式：
    permission: 'abc',
    permission: ['aaa', 'bbb'],
    permission: {code: ['aaa', 'bbb'], logic: 'or'},
    permission: {code: ['aaa', 'bbb'], class: ['c-2', 'c-3'], style: { width: '40px', height: '20px' }},
    permission: {code: ['aaa', 'bbb'], component: ElSwitch},
    // 路由特有，以重定向方式处理权限不足，参数与router.push相同
    permission: {code: 'xxx', route: '/403'}

    路由级别的权限控制，默认方式为跳转到403页面
 */
export default {
  install(app, router) {
    router.beforeEach((to, from, next) => {
      if (to.meta?.permission){
        // 判断权限
        routePermission(to, to.meta.permission, next);
        return;
      }

      next();
    });
  }
};


function routePermission(to, permission, next){
  let config = normalizeAuthConfig(permission);
  if (hasPermission(config.code, config.logic, config.tip)) {
    next();
    return;
  }
  let route = to.matched.last();

  if (config.component) {
    route.components.default = config.component;
    next();
    return;
  }

  if (config.route) {
    next(config.route);
    return;
  }

  if (config.route) {
    next(config.route);
    return;
  }

  let css = config.css;
  if (css.class || css.style) {
    addTypeHook(route.components.default, 'mounted', function pushVueCss(){
      addVueCss([this], css);
    });
    addTypeHook(route.components.default, 'updated', function pushVueCss(){
      addVueCss([this], css);
    });
    next();
    return;
  }



  // 默认方式，跳转到403页面
  next('/403');
  return;
}


function addTypeHook(type, name, fn) {
  let hook = type[name];
  if (hook?.fnName == fn.name) {
    return;
  }

  type[name] = function () {
    fn.apply(this);
    type[name].parent && type[name].parent.apply(this, arguments);
  };
  type[name].fnName = fn.name;
  type[name].parent = hook;

}